package it.fantacalcio.struts.action.user.account;

import it.fantacalcio.model.User;
import it.fantacalcio.spring.service.MyServiceFactory;
import it.fantacalcio.struts.form.UserForm;
import it.fantacalcio.utility.Utility;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ConfermaEditAccountAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		User userInSession = (User) request.getSession().getAttribute("userInSession");
		if(userInSession==null || userInSession.getAttivo().equals("NO")){
			return mapping.findForward("noninsession");
		}
		
		UserForm userForm = (UserForm) form;
		User user = new User();
		String username = null;
		String password = null;
		
		try {
			user = MyServiceFactory.getUserService().get(userForm.getId());
			username = user.getUsername();
			password = user.getPassword();
			if(!userForm.getPassword().equals(user.getPassword())){
				userForm.setPassword(Utility.md5hash(userForm.getPassword()));
			}
			BeanUtils.copyProperties(user, userForm);
			int risp = MyServiceFactory.getUserService().modifica(user);
			if(risp < 1){
				request.setAttribute("msg", "Account non modificato");
				return mapping.findForward("modifica");
			}
			request.getSession().setAttribute("userInSession", user);
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("error");
		}
		
		if(!user.getUsername().equals(username) || !user.getPassword().equals(password)){
			user = MyServiceFactory.getUserService().get(user.getId());
			request.setAttribute("username", user.getUsername());
			request.setAttribute("msg", "Sono stati modificati dati senzibili," +
									" la preghiamo di rieffettuare il login");
			return mapping.findForward("noninsession");
		}
		
		request.setAttribute("msg", "Account modificato con successo");
		return mapping.findForward("ok");
	}
	
}
